﻿using Dapper;
using InventoryIssue.API.Read.Application.Command.Allocate;
using InventoryIssue.Dtos;
using InventoryIssue.ErrorCode;
using InventoryIssue.Infrastructrue.Implement;
using MediatR;
using System.Text;

namespace InventoryIssue.API.Read.Application.Handler.Allocate
{
    public class GetAllocateProductHandler : IRequestHandler<GetAllocateProductCommand, APIResult<List<AllocateProductDto>>>
    {
        private readonly DatabaseContext db;

        public GetAllocateProductHandler(DatabaseContext db)
        {
            this.db = db;
        }
        public async Task<APIResult<List<AllocateProductDto>>> Handle(GetAllocateProductCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<AllocateProductDto>> result = new APIResult<List<AllocateProductDto>>();
            StringBuilder sql = new StringBuilder();
            sql.Append(@"SELECT
                        a.productId,
	                    a.ProductName,
	                    a.ProductCode,
	                    a.Specifications,
	                    a.Price,
	                    b.LocationName,
                        c.Id,
	                    c.AllocateId,
                        c.Quantity
                    FROM
	                    productmodel a
	                    JOIN locationmodel b ON a.LocationId = b.LocationId 
	                    JOIN allocateproductmodel c ON a.ProductId = c.ProductId
                    WHERE
	                    a.IsDel = 0 
	                    AND b.IsDel = 0
                        AND c.IsDel = 0
                        AND c.AllocateId = @AllocateId"
            );
            var parameters = new
            {
                AllocateId = request.AllocateId
            };
            var data = await db.DapperConnection.QueryAsync<AllocateProductDto>(sql.ToString(), parameters);
            result.Message = "显示成功";
            result.Code = APIEnum.Ok;
            result.Data = data.ToList();
            return result;
        }
    }
}
